package com.ruibang.glass.sale.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceCreate;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.sale.constant.Constants;
import com.ruibang.glass.sale.constant.SaleMenuIdCode;
import com.ruibang.glass.sale.domain.req.SaleBalanceReq;
import com.ruibang.glass.sale.entity.*;
import com.ruibang.glass.sale.feign.CamundaApi;
import com.ruibang.glass.sale.feign.FileApi;
import com.ruibang.glass.sale.mapper.SaleBalanceGoodsMapper;
import com.ruibang.glass.sale.service.*;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.model.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 结算单列表 服务实现类
 * </p>
 *
 * @author mameng
 * @since 2024-04-22
 */
@Service
public class SaleBalanceGoodsServiceImpl extends ServiceImpl<SaleBalanceGoodsMapper, SaleBalanceGoods> implements SaleBalanceGoodsService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private CamundaApi camundaApi;


    @Autowired
    private RedisSingleService rediservice;

    @Autowired
    private FileApi fileApi;

    @Autowired
    private SaleBalanceInvoiceService saleBalanceInvoiceService;
    @Autowired
    private SaleBalanceCollectionService saleBalanceCollectionService;
    @Autowired
    private SaleBalanceGoodsDetailService saleBalanceGoodsDetailService;

    @Override
    public IPage<SaleBalanceGoods> getPage(SaleBalanceReq saleBalanceReq) {
        LambdaQueryWrapper<SaleBalanceGoods> queryWrapper = Wrappers.<SaleBalanceGoods>lambdaQuery();
        if (StringUtils.isNotEmpty(saleBalanceReq.getPayType())) {
            queryWrapper.like(SaleBalanceGoods::getPayType, saleBalanceReq.getPayType());
        }
        Page<SaleBalanceGoods> saleContractManagementPage = baseMapper.selectPage(new Page<>(saleBalanceReq.getPageNo(), saleBalanceReq.getPageSize()),
                queryWrapper.orderByDesc(SaleBalanceGoods::getCreateTime)
        );
        if (CollectionUtils.isEmpty(saleContractManagementPage.getRecords())) {
            return saleContractManagementPage;
        }
        Map<Object, Object> userMap = rediservice.hmget(RedisKey.USER_GROUP_TYPE);
        List<String> businessKeys = saleContractManagementPage.getRecords().stream().map(SaleBalanceGoods::getId).collect(Collectors.toList());
        Map<String, BpmProcessInstanceStatus> processMap = null;
        //获取业务流程状态
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(businessKeys);
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            processMap = resultBody.getData().stream().collect(Collectors.toMap(bp -> bp.getBusinessKey(), bp -> bp, (bp1, bp2) -> bp1));
        }
//        for (SaleBalanceGoods saleBalanceGoods : saleContractManagementPage.getRecords()) {
//            Long count = saleBalanceCollectionService.count(Wrappers.<SaleBalanceCollection>lambdaQuery().eq(SaleBalanceCollection::getBalanceId, saleBalanceGoods.getId()));
//            Long count1 = saleBalanceInvoiceService.count(Wrappers.<SaleBalanceInvoice>lambdaQuery().eq(SaleBalanceInvoice::getBalanceId, saleBalanceGoods.getId()));
//            if (count.compareTo(0L)>0 && count1.compareTo(0L)>0){
//                saleBalanceGoods.setAllStatus(Constants.FOUR_STR);
//            }
//            if (count.compareTo(0L)>0 && count1.compareTo(0L)==0){
//                saleBalanceGoods.setAllStatus(Constants.THREE_STR);
//            }
//            if (count.compareTo(0L)==0 && count1.compareTo(0L)>0){
//                saleBalanceGoods.setAllStatus(Constants.TWO_STR);
//            }
//            if (count.compareTo(0L)==0 && count1.compareTo(0L)==0){
//                saleBalanceGoods.setAllStatus(Constants.ONE_STR);
//            }
//        }
        if (processMap != null){
            for (SaleBalanceGoods saleBalanceGoods : saleContractManagementPage.getRecords()) {
                if (processMap.get(saleBalanceGoods.getId()) != null) {
                    saleBalanceGoods.setStatus(String.valueOf(processMap.get(saleBalanceGoods.getId()).getStatus()));
                    saleBalanceGoods.setProcessId(processMap.get(saleBalanceGoods.getId()).getProcessInstanceId());
                    saleBalanceGoods.setApproveStatus(processMap.get(saleBalanceGoods.getId()).getResult());
                    saleBalanceGoods.setNodeName(processMap.get(saleBalanceGoods.getId()).getNodeName());
                    String userId = processMap.get(saleBalanceGoods.getId()).getUserId();
                    if (StringUtils.isNotBlank(userId)&& !StringUtils.equals(userId,"null")) {
                        if (userMap.get(userId)!=null){
                            saleBalanceGoods.setApproveUser(userMap.get(userId).toString());
                        }
                    }
                }
            }

        }
        return saleContractManagementPage;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSaleBalanceGoods(SaleBalanceGoods saleBalanceGoods) {
        baseMapper.insert(saleBalanceGoods);
        if (CollectionUtils.isNotEmpty(saleBalanceGoods.getSaleBalanceGoodsDetailList())) {
            for (SaleBalanceGoodsDetail saleBalanceGoodsDetail : saleBalanceGoods.getSaleBalanceGoodsDetailList()) {
                saleBalanceGoodsDetail.setBalanceId(saleBalanceGoods.getId());
                saleBalanceGoodsDetailService.save(saleBalanceGoodsDetail);
            }
        }
        BpmProcessInstanceCreate instanceCreate = new BpmProcessInstanceCreate();
        instanceCreate.setBusinessKey(saleBalanceGoods.getId());
        instanceCreate.setMenuId(SaleMenuIdCode.MENU_BALANCE_GOODS_ID.getMsg());
        //发起流程
        if (StringUtils.isNotBlank(saleBalanceGoods.getCreateUserId())) {
            Map<String, Object> variables = new HashMap<>();
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_STARTER_USER_ID, saleBalanceGoods.getCreateUserId());
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_BUSINESS_KEY, saleBalanceGoods.getId());
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_MENU_ID, SaleMenuIdCode.MENU_BALANCE_GOODS_ID.getMsg());
            instanceCreate.setVariables(variables);
        }
        commonService.startProcess(instanceCreate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSaleBalanceCollection(SaleBalanceGoods saleBalanceGoods) {
        saleBalanceCollectionService.remove(Wrappers.<SaleBalanceCollection>lambdaQuery().eq(SaleBalanceCollection::getBalanceId,saleBalanceGoods.getId()));
        if (CollectionUtils.isNotEmpty(saleBalanceGoods.getSaleBalanceCollectionList())) {
            for (SaleBalanceCollection saleBalanceCollection : saleBalanceGoods.getSaleBalanceCollectionList()) {
                saleBalanceCollection.setBalanceId(saleBalanceGoods.getId());
                saleBalanceCollectionService.save(saleBalanceCollection);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSaleBalanceInvoice(SaleBalanceGoods saleBalanceGoods) {
        saleBalanceInvoiceService.remove(Wrappers.<SaleBalanceInvoice>lambdaQuery().eq(SaleBalanceInvoice::getBalanceId,saleBalanceGoods.getId()));
        if (CollectionUtils.isNotEmpty(saleBalanceGoods.getSaleBalanceInvoiceList())) {
            for (SaleBalanceInvoice saleBalanceInvoice : saleBalanceGoods.getSaleBalanceInvoiceList()) {
                saleBalanceInvoice.setBalanceId(saleBalanceGoods.getId());
                saleBalanceInvoiceService.save(saleBalanceInvoice);
                if (CollectionUtils.isNotEmpty(saleBalanceInvoice.getFileIds())) {
                    FileBusiness fileBusiness = new FileBusiness();
                    fileBusiness.setFileIds(saleBalanceInvoice.getFileIds());
                    fileBusiness.setBusinessId(saleBalanceInvoice.getId());
                    fileApi.updateBusinessById(fileBusiness);
                }
            }
        }
    }

    @Override
    public SaleBalanceGoods getSaleBalanceGoodsById(String id) {
        SaleBalanceGoods saleBalanceGoods = baseMapper.selectById(id);
        List<SaleBalanceInvoice> saleBalanceInvoiceList = saleBalanceInvoiceService.list(Wrappers.<SaleBalanceInvoice>lambdaQuery().eq(SaleBalanceInvoice::getBalanceId, id));
        List<SaleBalanceCollection> saleBalanceCollectionList = saleBalanceCollectionService.list(Wrappers.<SaleBalanceCollection>lambdaQuery().eq(SaleBalanceCollection::getBalanceId, id));
        List<SaleBalanceGoodsDetail> saleBalanceGoodsDetails = saleBalanceGoodsDetailService.list(Wrappers.<SaleBalanceGoodsDetail>lambdaQuery().eq(SaleBalanceGoodsDetail::getBalanceId, id));
        if (CollectionUtils.isNotEmpty(saleBalanceInvoiceList)) {
            for (SaleBalanceInvoice saleBalanceInvoice : saleBalanceInvoiceList) {
                ResultBody<List<String>> fileIdsByBusinessId = fileApi.getFileIdsByBusinessId(saleBalanceInvoice.getId());
                if (fileIdsByBusinessId != null) {
                    saleBalanceInvoice.setFileIds(fileIdsByBusinessId.getData());
                }
            }
        }
        saleBalanceGoods.setSaleBalanceCollectionList(saleBalanceCollectionList);
        saleBalanceGoods.setSaleBalanceInvoiceList(saleBalanceInvoiceList);
        saleBalanceGoods.setSaleBalanceGoodsDetailList(saleBalanceGoodsDetails);
        return saleBalanceGoods;
    }


}
